<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    title="编辑膳食记录"
    width="600px"
  >
    <el-form :model="form" label-width="80px">
      <el-form-item label="餐次">
        <el-select v-model="form.mealType" style="width: 100%">
          <el-option
            v-for="type in mealTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="时间">
        <el-time-picker
          v-model="form.recordTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>

      <div class="selected-foods">
        <h4>食物明细</h4>
        <el-table :data="form.details" style="width: 100%">
          <el-table-column prop="food.name" label="食物名称" />
          <el-table-column label="数量" width="200">
            <template #default="{ row }">
              <el-input-number
                v-model="row.quantity"
                :min="0.1"
                :max="100"
                :step="0.1"
                style="width: 130px"
              />
              <span class="unit">{{ row.food.unit }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useStore } from 'vuex'

const props = defineProps({
  visible: Boolean,
  record: Object
})

const emit = defineEmits(['update:visible', 'confirm'])
const store = useStore()

const mealTypes = [
  { label: '早餐', value: '早餐', time: '08:00' },
  { label: '午餐', value: '午餐', time: '12:00' },
  { label: '晚餐', value: '晚餐', time: '18:00' },
  { label: '加餐', value: '加餐', time: '15:00' }
]

const form = ref({
  mealType: '',
  recordTime: '',
  details: []
})

// 监听 record 变化，更新表单数据
watch(() => props.record, (newRecord) => {
  if (newRecord) {
    form.value = {
      mealType: newRecord.mealType,
      recordTime: newRecord.recordTime?.substring(0, 5) || '',
      details: [...(newRecord.details || [])],
      recordId: newRecord.recordId
    }
  }
}, { immediate: true })

const handleConfirm = () => {
  emit('confirm', {
    ...form.value,
    userId: store.state.user.userInfo?.userId
  })
}
</script>

<style scoped>
.selected-foods {
  margin: 1rem 0;
  padding: 1rem;
  background: var(--el-fill-color-light);
  border-radius: 4px;
}

.selected-foods h4 {
  margin: 0 0 1rem;
  color: var(--el-text-color-primary);
}

.unit {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}
</style> 